package com.cnaaa.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.cnaaa.pay.bo.TradeQuery;
import com.cnaaa.pay.conf.AlipayConfigurationProperties;
import com.cnaaa.pay.entity.Trade;
import com.cnaaa.pay.service.AlipayService;
import com.cnaaa.pay.vo.alipay.TradePayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 2018/10/26 Create by 郭文梁
 * AlipayUtil
 * 支付宝服务封装
 *
 * @author 郭文梁
 * @date 2018/10/26
 */
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {
    private final AlipayConfigurationProperties configurationProperties;
    private final AlipayClient alipayClient;

    @Autowired
    public AlipayServiceImpl(AlipayConfigurationProperties configurationProperties, AlipayClient alipayClient) {
        this.configurationProperties = configurationProperties;
        this.alipayClient = alipayClient;
    }

    @Override
    public AlipayTradePagePayRequest buildTradePagePayRequest(TradePayVo tradePayVo) {
        String bizContent = JSON.toJSONString(tradePayVo);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(configurationProperties.getReturnUrl());
        request.setNotifyUrl(configurationProperties.getNotifyUrl());
        request.setBizContent(bizContent);
        return request;
    }

    @Override
    public String tradePay(AlipayTradePagePayRequest request) {
        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                return response.getBody();
            } else {//错误页面，暂时也返回支付宝错误页面
                return response.getBody();
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean checkReturnSign(Map<String, String> params) {
        String publicKey = configurationProperties.getPublicKey();
        String charset = configurationProperties.getCharset();
        String signType = configurationProperties.getSignType();
        try {
            return AlipaySignature.rsaCheckV1(params, publicKey, charset, signType);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String query(TradeQuery query) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent(JSON.toJSONString(query));
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            return null;
        }
    }

    @Override
    public AlipayTradeCloseResponse close(TradeQuery query) throws AlipayApiException {
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        request.setBizContent(JSON.toJSONString(query));
        return alipayClient.execute(request);
    }

    @Override
    public String pay(Trade trade) throws AlipayApiException {
        if (trade == null) {
            return "非法请求，(The order does not exist.)";
        }
        TradePayVo tradePayVo = new TradePayVo();
        tradePayVo.setBody(trade.getDescription());
        tradePayVo.setTradeNo(trade.getTradeNo());
        tradePayVo.setTotalAmount(trade.getAmount());
        tradePayVo.setSubject(trade.getName());
        AlipayTradePagePayRequest request = buildTradePagePayRequest(tradePayVo);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            log.error("Error at alipay API {}", response.getBody());
            return "创建支付失败";
        }
    }

    @Override
    public boolean close(Trade trade) throws AlipayApiException {
        //订单号
        String tradeNo = trade.getTradeNo();
        TradeQuery query = new TradeQuery();
        query.setOutTradeNo(tradeNo);
        AlipayTradeCloseResponse resp = close(query);
        int code = Integer.parseInt(resp.getCode());
        return code == 10000;
    }
}
